var ImagesUploadView = View.extend(ImagesUploadView = {
    search:false,
    selected_images_ids:[],
    selected_images_li:[],
    init: function() {
        this.load_images();
        this.setup_radio_tagging();
        this.setup_find_tagged_members();
        this.setup_image_click();
        this.bind_pagination_links();
    },

    setup_radio_tagging:function(){
        var self = this;
        
        $("#untagged").change(function(){
            $("#tagged_status").val($(this).val());
            self.search = false;
            $("#find_tagged_members_search_text").val('');
            $(".tagged_btn").hide('fast');
            self.load_images();
        });
        
        $("#tagged").change(function(){
            $("#tagged_status").val($(this).val());
            self.search = false;
            $("#find_tagged_members_search_text").val('');
            $(".tagged_btn").show('fast');
            self.load_images();
        });

        $("#untag_images_btn").click(function(){
            var count = self.selected_images_ids.length;
            if(count > 0){
                var ques = "Are You Sure You Want To Untag The Selected Images ?";
                if(count == 1){
                    ques = "Are You Sure You Want To Untag The Selected Image ?";
                }
                alertify.confirm( ques, function (e) {
                    if (e) {
                        self.untagImage();
                    } else {
                        //after clicking Cancel
                    }
                });
            }
            else{
                alert('At Least One Image Has To Be Selected Prior To This Action.')
            }
        });

        $("#delete_images_btn").click(function(){
            var count = self.selected_images_ids.length;
            if(count > 0){
                var ques = "Are You Sure You Want To Delete The Selected Images ?";
                if(count == 1){
                    ques = "Are You Sure You Want To Delete The Selected Image ?";
                }
                alertify.confirm( ques, function (e) {
                    if (e) {
                        self.deleteImage();
                    } else {
                        //after clicking Cancel
                    }
                });
            }
            else{
                alert('At Least One Image Has To Be Selected Prior To This Action.')
            }
        });

    },

    setup_find_tagged_members:function(){
        var self = this;
        $("#find_tagged_members_btn").click(function(){
            var search_query = $("#find_tagged_members_search_text").val();
            var test = search_query.trim();
            if(test.length > 0){
                $("#untagged").parents().removeClass('active');
                $("#tagged").parents().addClass('active');
                self.search = true;
                $("#tagged_status").val($("#tagged").val());
                $("#untag_images_btn").show('fast');
                self.load_images();
            }
        });

        $("#search_form").submit(function(e){
            e.preventDefault();
            $("#find_tagged_members_btn").click();

            return false;
        });
    },


    setup_image_click:function(){
        var self = this;
        $(".image-item .click-area, .image-item a.closer").live('click',function(){
            var li = $(this).parents('li');
            if($(this).hasClass('click-area')){
                var icon_tag = $(this).parent().find('a.closer i');
            }
            else{
                var icon_tag = $(this).find('i');
            }

            if(li.hasClass('selected_image')){
                li.removeClass('selected_image');
                icon_tag.removeClass('fa fa-check');
            }
            else{
                li.addClass('selected_image');
                icon_tag.addClass('fa fa-check');
            }
            self.selected_images_ids = [];
            self.selected_images_li = [];
            $("li.image-item").each(function(){
                var next_li = $(this);
                if(next_li.hasClass('selected_image')){
                    var id = next_li.attr('data-org-mem-image-id');
                    self.selected_images_ids.push(id);
                    self.selected_images_li.push(next_li);
                }
            });
        });
    },


    bind_pagination_links:function(){
        var self = this;
        $("ul.pagination li a").live('click',function(e){
            e.preventDefault();
            var href = $(this).attr('href');
            var page = href.slice(-1);// /memberz/images/load_member_images/3
            self.load_images(page);
        });
    },


    load_images: function(page) {
        var self = this;
        self.hide_content();
        self.show_loader();
        var include_search = false;
        var search_query = $("#find_tagged_members_search_text").val();
        search_query = search_query.trim();
        var params = {
            'filter': $("#tagged_status").val()
        };
        if(self.search){
            params['search'] = search_query
        }
        if(typeof page == "undefined"){
            page = 1;
        }
        var url = $("#images-data-url").val() + "/"+page;

        $.ajax({
            url: url,
            data:params,
            dataType: 'json',
            type: 'post',
            success: function(res) {

                if(res.status == 'success'){
                    self.renderImages(res);
                    self.hide_loader();
                    self.show_content();
                }
                else{
                    self.loader_warning(res.message);
                }
            },
            error: function(xhr) {
                self.loader_danger("Server Error");
                console.log(xhr.responseText);
            }
        });
    },

    renderImages:function(data){
        var self = this;
        var ul = $('#gallery ul#images');
        var tag_list_url = $("#tag-list-url").val();
       /* ul.html('');
        var lis = "";
        for(var d in data){
            var x = data[d];
            var member_image = x['MemberImage'];
            var org_member_image = x['OrganisationMemberImage'];
            var org_member = x['OrganisationMember'];
            var image_id = member_image['id'];
            var org_mem_image_id = org_member_image['id'];
            var image_thumb = member_image['thumb_path'];
            var image_url = member_image['url'];
            lis += "<li class='image-item' data-image-id='"+image_id+"' data-org-mem-image-id='"+org_mem_image_id+"' style='background-image: url("+image_url+");'>";
            lis += "    <div class='click-area' style='width: auto; height: 80%;'>&nbsp;</div>";
            //lis += "    <a href='#' class='closer'><i class='fa fa-times'></i></a>";
            lis += "    <a href='#' class='closer'><i class=''></i></a>";
            if(org_member.id){
                lis += "    <div class='tag_area'>";
                var mem = org_member['Member'];
                var full_name = mem['full_name'];
                lis += "        <input type='text' disabled class='tag_list input input-medium ui-autocomplete-input tagged' data-value='"+full_name+"' value='"+full_name+"' placeholder='Who is this?' data-url='"+tag_list_url+"' autocomplete='off' role='textbox' aria-autocomplete='list' aria-haspopup='true'>";
                lis += "        <a href='javascript:void(0);' class='tag_remove' style='display: block' ><i class='fa fa-times'></i></a>";
            }
            else{
                lis += "    <div class='tag_area'>";
                lis += "        <input type='text' class='tag_list input input-medium ui-autocomplete-input' placeholder='Who is this?' data-url='"+tag_list_url+"' autocomplete='off' role='textbox' aria-autocomplete='list' aria-haspopup='true'>";
                lis += "        <a href='javascript:void(0);' class='tag_remove'><i class='fa fa-times'></i></a>";
            }
            lis += "    </div>";
            lis += "    <div class='inner-loader text-center hide'><i class='fa fa-spinner fa-spin fa-3x'></i></div>";
            lis += "    <div class='mini-blanket hide'></div>";
            lis += "</li>";
        }*/
        ul.html(data.render);

        $(".tag_list").autocomplete({
            source: tag_list_url,
            minLength: 2,
            select: function(event, ui) {
                $(this).val( ui.item.value.name );
                $(this).data("tag-id", ui.item.value.id );
                $(this).attr("disabled", true).addClass('tagging');
                $(this).parent().find(".tag_remove").show();
                self.tagImage($(this),ui);
                event.preventDefault();
            },
            focus: function(event, ui) {
                $(this).val( ui.item.value.name );
                event.preventDefault();
            },
            change: function(event, ui) {
                if( ui.item ) {
                    $(this).val( ui.item.value.name );
                    event.preventDefault();
                }
            },
            create: function() {
                $(this).data('ui-autocomplete')._renderItem = function( ul, item ) {
                    return $("<li class='bg-white b-b text-sm'>").append("<span class='p-xs block'>" + item.label + "</span>").appendTo(ul);
                };

                $(this).data('ui-autocomplete')._resizeMenu = function() {
                    this.menu.element.outerWidth(275);
                };
            }
        }).blur(function(){
            var input = $(this);
            var def_val = input.attr('data-value');
            if(!input.hasClass('tagging') && input.hasClass('tagged') ){
                input.attr("disabled", true).val(def_val);
                input.parent().find(".tag_remove").show();
            }
        });


       $(".tag_remove").click(function() {
            if($(this).find("i").hasClass('fa-times')){
                $(this).hide();
                var input = $(this).parent().find(".tag_list");
                input.removeAttr("disabled").removeData("tag-id").removeClass("tagging").val("").focus();
            }
        });

       /* $(".closer").click(function() {
            if($(this).find("i").hasClass('fa-times')){
                if( !confirm("Remove tag from this image?") ) {
                    return;
                }
                var closer = $(this);
                
                self.untagImage( $(this).parents('li').data('org-mem-image-id'), function() {
                    closer.parents("li").hide('fast').remove();
                });
            }
        });*/
    },

    
    untagImage: function() {
        var self = this;
        var url = $("#untag-image-url").val();
        var params = {
            'organisation_member_image_id': self.selected_images_ids
        };
        
        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(response) {
                if( response.status == 'success' ) {
                    alertify.success( response.message);
                    self.after_untag();
                }
                else {
                    alertify.error( response.message );
                }
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    },


    after_untag:function(){
        var self = this;
        $("#images-list ul#images li.selected_image").hide('fast').remove();
        self.selected_images_ids = [];
    },

    deleteImage: function() {
        var self = this;
        var url = $("#delete-image-url").val();
        var params = {
            'organisation_member_image_id': self.selected_images_ids
        };

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(response) {
                if( response.status == 'success' ) {
                    alertify.success( response.message);
                    self.after_untag();
                }
                else {
                    alertify.error( response.message );
                }
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    },


    tagImage:function($this,ui){
        var self = this;
        self.tagLoader($this,'show');
        var li = $this.parent().parent();
        var div_tag_area = $this.parent();
        var member_image_id = li.attr('data-image-id');
        var org_mem_image_id = li.attr('data-org-mem-image-id');
        var member_id = ui.item.value.id;
        var org_mem_id = ui.item.value.org_mem_id;
        var query = "member_id="+member_id+"&member_image_id="+member_image_id+"&org_mem_image_id="+org_mem_image_id+"&org_mem_id="+org_mem_id;
        var url = $("#tag-image-url").val();

        $.ajax({
            url: url,
            data: query,
            dataType: 'json',
            type: 'post',
            success: function(res) {
                if(res.status == 'success'){
                    alertify.success(res.message);
                    div_tag_area.css("background-color: #80c740;")
                    self.tagLoader($this,'hide');
                    $this.parents("li").hide('fast').remove();
                }
                else{
                    self.tagLoaderWarning($this,res.message);
                }
            },
            error: function(xhr) {
                alertify.error("Internal Server Error");
                self.tagLoaderDanger($this);
                console.log(xhr.responseText);
            }
        });
    },

    tagLoader:function($this,type){
        var li = $this.parent().parent();
        li.find(".inner-loader i").removeClass('fa-warning text-warning text-danger').addClass('fa-spinner fa-spin').html("");
        if(typeof type == 'undefined'){
            type = 'show';
        }
        if(type == 'show'){
            li.find(".inner-loader").removeClass('hide');
            li.find(".mini-blanket").removeClass('hide');
        }
        else{
            li.find(".inner-loader").addClass('hide');
            li.find(".mini-blanket").addClass('hide');
        }
    },

    tagLoaderWarning:function($this,txt){
        var self = this;
        if(typeof txt == 'undefined'){
            txt = 'Tagging Failed';
        }
        var li = $this.parent().parent();
        li.find(".inner-loader i").removeClass('fa-spinner fa-spin').addClass('fa-warning text-warning').html("<span style='font-size: 15px;'>"+txt+"</span>");
        _.delay(function(){
            self.tagLoader($this,'hide');
        }, 2000);
    },

    tagLoaderDanger:function($this,txt){
        var self = this;
        if(typeof txt == 'undefined'){
            txt = 'Server Error';
        }
        var li = $this.parent().parent();
        li.find(".inner-loader i").removeClass('fa-spinner fa-spin').addClass('fa-warning text-danger').html("<span style='font-size: 15px;'>"+txt+"</span>");
        _.delay(function(){
            self.tagLoader($this,'hide');
        }, 2000);
    },

    show_loader:function(txt){
        var self = this;
        self.animate_loader(txt,'fadeOutLeftBig','fadeInRightBig','show');
    },

    hide_loader:function(txt){
        var self = this;
        self.animate_loader(txt,'fadeInRightBig','fadeOutLeftBig','hide');
    },

    loader_warning:function(txt){
        var gl = $('#galleryLoading');
        if(typeof txt == 'undefined'){
            txt = "Some Warning Message Here"; //Default
        }
        gl.find('h3.text-muted').html(txt);
        $('#spinner_wrapper i').removeClass('fa-spinner fa-spin').addClass('fa-warning text-warning');
    },

    loader_danger:function(txt){
        var gl = $('#galleryLoading');
        if(typeof txt == 'undefined'){
            txt = "Some Danger Message Here"; //Default
        }
        gl.find('h3.text-muted').html(txt);
        $('#spinner_wrapper i').removeClass('fa-spinner fa-spin').addClass('fa-warning text-danger');
    },

    animate_loader:function(txt,remove_class,add_class,type){
        var self = this;
        var gl = $('#galleryLoading');
        if(typeof txt == 'undefined'){
            txt = "Loading member images. Please wait ..."; //Default
        }
        gl.find('h3.text-muted').html(txt);
        $('#spinner_wrapper i').removeClass('fa-warning text-warning').addClass('fa-spinner fa-spin');
        if(type == 'show'){
            gl.show();
            gl.removeClass('hide');
        }
        gl.removeClass(remove_class).addClass(add_class);
        if(type == 'hide'){
            _.delay(function(){
                gl.hide();
            }, 1000);
        }
    },


    show_content:function(){
        var self = this;
        self.animate_content('fadeOutUp','fadeInUpBig','show');
    },

    hide_content:function(){
        var self = this;
        self.animate_content('fadeInUpBig','fadeOutUp','hide');
    },

    animate_content:function(remove_class,add_class,type){
        var self = this;
        var gallery = $('#gallery');
        if(type == 'hide'){
           if(gallery.hasClass('hide')){
               return; //If it is already hidden then leave it
           }
        }
        if(type == 'show'){
            gallery.removeClass('hide').addClass('stay');
        }
        gallery.removeClass(remove_class).addClass(add_class);
        if(type == 'hide'){
           _.delay(function(){
               if(!gallery.hasClass('stay')){
                   gallery.addClass('hide').removeClass('stay');
               }
            }, 1000);
        }
    },


    test_extra_param_callback:function(p){
        console.log('i processed and pass extra params that we want to send with File upload');
        //You can even change the data to pass dynamically before this function get called by the file upload manager
        var params={
            param1:'data1',
            param2:'data2'
        };
        return params;
    },

    image_upload_callback:function(p){
        var self = this;
        $("#tagged").parent().removeClass('active');
        $("#untagged").change().parent().addClass('active');
    }
});
var admin_images = null;
$(document).ready(function() {
    admin_images = new ImagesUploadView();
});